package com.minggo.charmword.activity;

import java.io.File;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;

import com.google.gson.Gson;
import com.minggo.charmword.R;
import com.minggo.charmword.cache.CacheUtils;
import com.minggo.charmword.listener.SimpleZoomListener;
import com.minggo.charmword.model.User;
import com.minggo.charmword.model.ZoomState;
import com.minggo.charmword.service.CharmWordApplication;
import com.minggo.charmword.util.PhotoUtil;
import com.minggo.charmword.util.SharePreferenceUtil;
import com.minggo.charmword.view.ImageZoomView;

/**
 * 对头像图片进行框选
 * @author liangchunrong
 * @time 2014-4-10 下午6:17:08
 */
public class ImageClipActivity extends Activity {
	private String imagePath = "";
	private Button save_btn;
	private ImageZoomView mZoomView;
	private ZoomState mZoomState;
	private Bitmap mBitmap;
	private SimpleZoomListener mZoomListener;
	private View iv_back;
	private int width;
	private int height;
	private Bitmap bitmap1;
	private int mwidth;
	
	private User user;
	
    public static final int RETURN_IMAGE = 11000;
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_imageview_zoom);
		user = new Gson().fromJson(CacheUtils.getInstance().getDiskCache("user_info"), User.class);
		
		width = getResources().getDisplayMetrics().widthPixels; // 屏幕的宽
		height = getResources().getDisplayMetrics().heightPixels;// 屏幕的高
		imagePath = getIntent().getExtras().getString("imagePath");
		mZoomView = (ImageZoomView) findViewById(R.id.photoView);
		mwidth = width
				- (int) getResources().getDimension(
						R.dimen.dp_50) * 2;
		iv_back = findViewById(R.id.lo_clip_image_back);
		save_btn = (Button) findViewById(R.id.bt_image_save);

		save_btn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				new Thread(new Runnable() {
					public void run() {
						String savePath = Environment.getExternalStorageDirectory().getPath() + "/minggo.charmword/user/images/" + System.currentTimeMillis() + ".jpg";
						Bitmap bitmap = getBitmapFromView(mZoomView);
						if (bitmap != null) {
							bitmap1 = Bitmap.createBitmap(bitmap, width / 2
									- mwidth / 2, height / 2 - mwidth / 2,
									mwidth, mwidth, null, true);
							//bitmap1 = PhotoUtil.comp(bitmap1);
							if (bitmap1 != null) {
								PhotoUtil.writeToFile(savePath, bitmap1, 10);
								if (bitmap != null) {
									bitmap.recycle();
								}
								if (bitmap1 != null) {
									bitmap1.recycle();
								}
							} 
							if (user!=null) {
								SharePreferenceUtil.saveString(ImageClipActivity.this, savePath, user.userId+"avatar");
								setResult(RETURN_IMAGE);
							}
							finish();
						}

					}
				}).start();

			}
		});
		iv_back.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				onBackPressed();
			}
		});
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				
				mBitmap = BitmapFactory.decodeFile(imagePath);
				handler.sendEmptyMessage(0);
			}
		});
		thread.start();
		CharmWordApplication.allActivities.add(this);
	}

	private Bitmap getBitmapFromView(View view) {
		Bitmap bitmap = null;
		try {
			int width = view.getWidth();
			int height = view.getHeight();
			if (width != 0 && height != 0) {
				bitmap = Bitmap.createBitmap(width, height,
						Bitmap.Config.ARGB_4444);
				Canvas canvas = new Canvas(bitmap);
				view.layout(0, 0, width, height);
				view.draw(canvas);
			}
		} catch (Exception e) {
			bitmap = null;
			e.getStackTrace();
		}
		return bitmap;
	}

	private Handler handler = new Handler(new Callback() {
		
		@Override
		public boolean handleMessage(Message msg) {
			mZoomView.setImage(mBitmap);
			mZoomState = new ZoomState();
			mZoomView.setZoomState(mZoomState);
			mZoomListener = new SimpleZoomListener();
			mZoomListener.setZoomState(mZoomState);
			mZoomView.setOnTouchListener(mZoomListener);
			resetZoomState();
			return false;
		}
	});

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mBitmap != null)
			mBitmap.recycle();
		File file = new File(imagePath);
		if(file.exists()){
			file.delete();
		}
	}

	private void resetZoomState() {
		mZoomState.setPanX(0.5f);
		mZoomState.setPanY(0.5f);
		mZoomState.setZoom(1f);
		mZoomState.notifyObservers();
	}

	public void onBackPressed() {
		super.onBackPressed();
		finish();
	}

}
